package com.heisen.base.utils;

import java.math.BigDecimal;

public class BigDecimalUtil {
	// 默认保留2位小数
	private static final int DEFAULT_DIV_SCALE = 2;

	private BigDecimalUtil() {
	}

	/**
	 * 多个BigDecimal相加
	 */
	public static BigDecimal sum(BigDecimal[] values) {
		BigDecimal total = BigDecimal.ZERO;
		for (BigDecimal value : values) {
			if (value != null) {
				total = total.add(value);
			}
		}
		return total;
	}

	/**
	 * 多个BigDecimal相加
	 */
	public static BigDecimal add(BigDecimal... values) {
		BigDecimal result = BigDecimal.ZERO;
		for (BigDecimal value : values) {
			if (value != null) {
				result = result.add(value);
			}
		}
		return result;
	}

	/**
	 * BigDecimal相减
	 */
	public static BigDecimal sub(BigDecimal from, BigDecimal to) {
		if (from == null) {
			return BigDecimal.ZERO.subtract(to);
		}

		if (to == null) {
			return from;
		}

		return from.subtract(to);
	}


	/**
	 * 多个BigDecimal相乘, 设置精度scale
	 */
	public static BigDecimal mul(int scale, BigDecimal... values) {
		if (values.length == 0) {
			throw new IllegalArgumentException("no values to calculate");
		}

		BigDecimal result = values[0];
		for (int i = 1, length = values.length; i < length; i++) {
			BigDecimal value = values[i];
			if (value != null) {
				result = result.multiply(value);
			}
		}

		return result.setScale(2, BigDecimal.ROUND_HALF_UP);
	}

	/**
	 * 多个BigDecimal相除, 精度scale为2
	 */
	public static BigDecimal div(BigDecimal... values) {
		return div(DEFAULT_DIV_SCALE, values);
	}

	/**
	 * 多个BigDecimal相除, 设置精度scale
	 */
	public static BigDecimal div(int scale, BigDecimal... values) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		if (values.length == 0) {
			throw new IllegalArgumentException("no values to calculate");
		}
		BigDecimal result = values[0];
		for (int i = 1, length = values.length; i < length; i++) {
			BigDecimal value = values[i];
			if (value != null) {
				result = result.divide(value, scale, BigDecimal.ROUND_HALF_UP);
			}
		}

		return result;
	}

	/**
	 * 对double值保留指定位数
	 */
	public static double getDoubleValByScale(double val, int scale) {
		double pow = Math.pow(10.0, scale);
		return (double)Math.round(val * pow) / pow;
	}
}
